package com.kakarote.admin.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.kakarote.admin.common.AdminCodeEnum;
import com.kakarote.admin.entity.BO.AdminLanguagePackBO;
import com.kakarote.admin.entity.BO.AdminLanguagePackTypeBO;
import com.kakarote.admin.entity.PO.AdminConfig;
import com.kakarote.admin.entity.PO.AdminLanguagePack;
import com.kakarote.admin.entity.PO.AdminUserConfig;
import com.kakarote.admin.entity.VO.AdminLanguagePackVO;
import com.kakarote.admin.mapper.AdminLanguagePackMapper;
import com.kakarote.admin.service.IAdminConfigService;
import com.kakarote.admin.service.IAdminLanguagePackRelService;
import com.kakarote.admin.service.IAdminLanguagePackService;
import com.kakarote.admin.service.IAdminUserConfigService;
import com.kakarote.common.log.entity.OperationLog;
import com.kakarote.core.common.enums.SystemCodeEnum;
import com.kakarote.core.entity.BasePage;
import com.kakarote.core.entity.PageEntity;
import com.kakarote.core.exception.CrmException;
import com.kakarote.core.feign.admin.entity.AdminLanguagePackFieldBO;
import com.kakarote.core.servlet.BaseServiceImpl;
import com.kakarote.core.utils.ExcelParseUtil;
import com.kakarote.core.utils.UserUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 语言包表 服务实现类
 * </p>
 *
 * @author zmj
 * @since 2020-12-01
 */
@Slf4j
@Service
public class AdminLanguagePackServiceImpl extends BaseServiceImpl<AdminLanguagePackMapper, AdminLanguagePack> implements IAdminLanguagePackService {

    @Autowired
    private IAdminUserConfigService adminUserConfigService;

    @Autowired
    private IAdminConfigService adminConfigService;

    @Autowired
    private IAdminLanguagePackRelService adminLanguagePackRelService;

    @Autowired
    private IAdminLanguagePackService adminLanguagePackService;

    private static final String DEFAULT_LANGUAGE_PACK = "DefaultLanguagePack";

    private static final String DEFAULT_LANGUAGE_PACK_DESCRIBE = "设置默认语言包";

    private static final String LANGUAGE_PACK_CHINESE = "zh-CN";

    /**
     * 默认的分隔符
     */
    private static final String DEFAULT_SPLIT = "\\.";

    private static final int SYSTEM = 0;
    private static final int USER = 1;

    private static final int PC = 1;
    private static final int APP = 2;

    private static final String PC_FLAG = "";
    private static final String APP_FLAG = "mobile.";

    @Override
    public BasePage<AdminLanguagePackVO> queryLanguagePackList(AdminLanguagePackBO adminLanguagePackBO, Integer systemOrUser) {
        BasePage<AdminLanguagePackVO> languagePackBasePage = getBaseMapper().queryLanguagePackList(adminLanguagePackBO.parse(), adminLanguagePackBO.getLanguagePackType());
        List<AdminLanguagePackVO> packBasePageList = languagePackBasePage.getList();
        if (CollectionUtil.isEmpty(packBasePageList)) {
            return new BasePage<>();
        }
        List<AdminLanguagePackVO> customerList = new ArrayList<>();
        JSONObject deflautLanguagePack = queryDeflautLanguagePackSetting(systemOrUser, adminLanguagePackBO.getLanguagePackType(), false);
        Object packId = deflautLanguagePack.get("languagePackId");
        if (ObjectUtil.isNotEmpty(packId)) {
            String s = StrUtil.toString(packId);
            if (NumberUtil.isNumber(s)) {
                Long languagePackId = Long.parseLong(s);
                packBasePageList.stream().collect(Collectors.toMap(AdminLanguagePackVO::getLanguagePackName, Function.identity(), (v1, v2) -> v2)).values().forEach(adminLanguagePackVO -> {
                    if (adminLanguagePackVO.getLanguagePackId().equals(languagePackId)) {
                        adminLanguagePackVO.setDefaultLanguage(1);
                    }
                    customerList.add(adminLanguagePackVO);
                });
                List<AdminLanguagePackVO> collect = packBasePageList.stream().filter(item -> item.getDefaultLanguage().equals(1)).collect(Collectors.toList());
                if (CollectionUtil.isEmpty(collect) && adminLanguagePackBO.getPage().equals(1)) {
                    packBasePageList.get(0).setDefaultLanguage(1);
                }
            }
        }
        languagePackBasePage.setList(customerList);
        return languagePackBasePage;
    }

    @Override
    public void addOrUpdateLanguagePack(MultipartFile file, AdminLanguagePackBO adminLanguagePackBO) {

        //查询当前语言包
        AdminLanguagePack languagePack = getBaseMapper().queryLanguagePackById(adminLanguagePackBO.getLanguagePackId());
        //获取当前语言包所有类型
        List<AdminLanguagePack> list = new ArrayList<>();
        if (BeanUtil.isNotEmpty(languagePack)) {
            list = lambdaQuery().eq(AdminLanguagePack::getLanguagePackName, languagePack.getLanguagePackName()).list();
        }
        Map<Integer, AdminLanguagePack> typeMap = getTypeMap(list);

        String filePath = getFilePath(file);
        AtomicReference<Integer> num = new AtomicReference<>(0);

        AtomicReference<JSONObject> appObject = new AtomicReference<>(new JSONObject());
        AtomicReference<JSONObject> pcObject = new AtomicReference<>(new JSONObject());
        ExcelUtil.readBySax(filePath, "0", (int sheetIndex, long rowIndex, List<Object> rowList) -> {
            if (rowIndex > 0) {
                num.getAndSet(num.get() + 1);
                String filedName = rowList.get(0).toString().trim();
                String filedCustom = "";
                int sizeIndex = 2;
                if (rowList.size() > sizeIndex) {
                    Object o = rowList.get(2);
                    if (ObjectUtil.isNotEmpty(o)) {
                        String s = StrUtil.toString(o);
                        if (StrUtil.isNotBlank(s)) {
                            filedCustom = s.trim();
                        }
                    }
                }
                String index = ".";
                String[] filedNameArr = filedName.split(DEFAULT_SPLIT);
                List<String> arrList = new ArrayList<>(Arrays.asList(filedNameArr));
                if (filedName.contains(index)) {
//                    getJsonObject(jsonObject.get(), arrList,CollectionUtil.getLast(arrList), filedCustom);
                    if (filedName.startsWith(APP_FLAG)) {
                        appObject.get().fluentPut(filedName, filedCustom);
                    } else {
                        pcObject.get().fluentPut(filedName, filedCustom);
                        if (!checkUuid(CollectionUtil.getLast(arrList))) {
                            appObject.get().fluentPut(filedName, filedCustom);
                        }
                    }
                } else {
//                    jsonObject.get().fluentPut(filedName, filedCustom);
                    if (filedName.startsWith(APP_FLAG)) {
                        appObject.get().fluentPut(filedName, filedCustom);
                    } else {
                        pcObject.get().fluentPut(filedName, filedCustom);
                        if (!checkUuid(CollectionUtil.getLast(arrList))) {
                            appObject.get().fluentPut(filedName, filedCustom);
                        }
                    }
                }
            }
        });

        //添加pc语言包
        addLanguagePack(typeMap, adminLanguagePackBO.getLanguagePackName(), pcObject.get(), PC);
        //添加app语言包
        addLanguagePack(typeMap, adminLanguagePackBO.getLanguagePackName(), appObject.get(), APP);

    }

    public Long addLanguagePack(Map<Integer, AdminLanguagePack> typeMap, String name, JSONObject jsonObject, Integer type) {
        if (ObjectUtil.isEmpty(jsonObject) || ObjectUtil.isEmpty(name)) {
            return 0L;
        }

        AdminLanguagePack adminLanguagePackPO = new AdminLanguagePack();
        adminLanguagePackPO.setLanguagePackName(name);
        if (typeMap.containsKey(type)) {
            AdminLanguagePack pack = typeMap.get(type);
            if (ObjectUtil.isNotEmpty(pack.getSysDefault()) && pack.getSysDefault().equals(SYSTEM)) {
                return pack.getLanguagePackId();
            } else {
                adminLanguagePackPO.setLanguagePackId(pack.getLanguagePackId());
            }
        } else {
            adminLanguagePackPO.setCreateTime(LocalDateTimeUtil.now());
        }
        adminLanguagePackPO.setLanguagePackContext(jsonObject.toString());
        adminLanguagePackPO.setCreateUserId(UserUtil.getUserId());
        adminLanguagePackPO.setSysDefault(USER);
        adminLanguagePackPO.setUpdateTime(LocalDateTime.now());
        adminLanguagePackPO.setLanguagePackType(type);
        saveOrUpdate(adminLanguagePackPO);
        return adminLanguagePackPO.getLanguagePackId();
    }


    public Map<Integer, AdminLanguagePack> getTypeMap(List<AdminLanguagePack> list) {
        if (CollectionUtil.isEmpty(list)) {
            return new HashMap<>();
        }
        return list.stream()
                .filter(item -> ObjectUtil.isNotEmpty(item.getLanguagePackType()))
                .sorted(Comparator.comparing(AdminLanguagePack::getLanguagePackId))
                .collect(Collectors.toMap(AdminLanguagePack::getLanguagePackType, Function.identity(), (v1, v2) -> v2));
    }

    @Override
    public OperationLog deleteLanguagePackById(Long id) {
        List<AdminUserConfig> adminUserConfigs = adminUserConfigService.queryUserConfigByNameAndValue(DEFAULT_LANGUAGE_PACK, id.toString());
        if (!adminUserConfigs.isEmpty()) {
            throw new CrmException(AdminCodeEnum.ADMIN_LANGUAGE_PACK_EXIST_USER_ERROR);
        }
        AdminLanguagePack byId = getBaseMapper().queryLanguagePackById(id);
        if (BeanUtil.isEmpty(byId)) {
            throw new CrmException();
        }
        if (SYSTEM == byId.getSysDefault()) {
            throw new CrmException(AdminCodeEnum.ADMIN_LANGUAGE_PACK_EXIST_USER_ERROR);
        }
        removeById(id);

        OperationLog operationLog = new OperationLog();
        operationLog.setOperationObject(byId.getLanguagePackName());
        operationLog.setOperationInfo("删除语言包：" + byId.getLanguagePackName());
        return operationLog;
    }

    @Override
    public void exportLanguagePackById(Long id, HttpServletResponse response) {
        //根据id查询语言包信息
        AdminLanguagePack adminLanguagePack = getBaseMapper().queryLanguagePackById(id);
        List<Map<String, Object>> objectList = new ArrayList<>();
        //查询各模块需要导出的翻译信息
        List<Map<String, Object>> allLanguagePackRel = adminLanguagePackRelService.getAllLanguagePackRel();
        //获取中文包信息
        List<AdminLanguagePack> chineseLanguagePacks = getBaseMapper().queryLanguagePackByName(LANGUAGE_PACK_CHINESE, 1);
        if (CollectionUtil.isEmpty(chineseLanguagePacks)) {
            throw new CrmException(AdminCodeEnum.ADMIN_LANGUAGE_PACK_CHOINESE_ERROR);
        }
        JSONObject chineseLanguageContext = new JSONObject();
        Map<Integer, AdminLanguagePack> typeMap = getTypeMap(chineseLanguagePacks);
        typeMap.forEach((item, value) -> {
            JSONObject jsonObject = JSONObject.parseObject(value.getLanguagePackContext());
            chineseLanguageContext.fluentPutAll(jsonObject);
        });
        //获取翻译包信息
        JSONObject translateObject = new JSONObject();
        JSONObject jsonObjectBefore = JSONObject.parseObject(adminLanguagePack.getLanguagePackContext());
        translateObject.fluentPutAll(jsonObjectBefore);
        //获取所属所有语言包信息并合并到需要导出对象中
        List<AdminLanguagePack> translateList = lambdaQuery().eq(AdminLanguagePack::getLanguagePackName, adminLanguagePack.getLanguagePackName()).list();
        if (CollectionUtil.isNotEmpty(translateList)) {
            Map<Integer, AdminLanguagePack> transTypeMap = getTypeMap(translateList);
            transTypeMap.forEach((item, value) -> {
                JSONObject jsonObject = JSONObject.parseObject(value.getLanguagePackContext());
                translateObject.fluentPutAll(jsonObject);
            });
        }
        Map<String, String> translateMap = getFilePath(translateObject.toString());
        Map<String, String> chineseMap = getFilePath(chineseLanguageContext.toString());
        //以中文语言包为基础进行导出，（key,中文,译文）
        chineseMap.forEach((k, v) -> {

            if (CollectionUtil.isNotEmpty(allLanguagePackRel)) {
                //更新需要翻译中的中文名称
                List<Map<String, Object>> fileName = allLanguagePackRel.stream().filter(item -> StrUtil.toString(item.get("fileName")).equals(StrUtil.toString(k))).collect(Collectors.toList());
                if (CollectionUtil.isNotEmpty(fileName)) {
                    Map<String, Object> last = CollectionUtil.getLast(fileName);
                    if (CollectionUtil.isNotEmpty(last) && last.containsKey(k)) {
                        Object o = last.get(k);
                        if (ObjectUtil.isNotEmpty(o) && (!v.equals(StrUtil.toString(o)))) {
                            v = StrUtil.toString(o);
                        }
                    }
                }
                //去除默认的
                allLanguagePackRel.removeIf(item -> StrUtil.toString(item.get("fileName")).equals(StrUtil.toString(k)));
            }
            Map<String, Object> record = new HashMap<>();
            record.put("fileName", k);
            record.put("chinese", v);
            String s = translateMap.get(k);
            if (ObjectUtil.isEmpty(s) || StrUtil.isBlank(s)) {
                s = "";
            }
            record.put("translateName", s);
            //重复key有值优先
            if ("customField.business.businessName".equals(k)) {
                System.out.println(k);
            }
            List<Map<String, Object>> collect = objectList.stream().filter(item -> StrUtil.toString(item.get("fileName")).equals(StrUtil.toString(k))).collect(Collectors.toList());
            if (CollectionUtil.isNotEmpty(collect)) {
                Map<String, Object> first = CollectionUtil.getFirst(collect);
                if (ObjectUtil.isEmpty(first.get(k)) && ObjectUtil.isNotEmpty(s)) {
                    first.put("translateName", s);
                }
            } else {
                objectList.add(record);
            }
        });
        if (CollectionUtil.isNotEmpty(allLanguagePackRel)) {
            List<Map<String, Object>> distinctList = allLanguagePackRel.stream()
                    .collect(Collectors.collectingAndThen(
                            Collectors.toCollection(() ->
                                    new TreeSet<>(Comparator.comparing(value -> StrUtil.toString(value.get("fileName"))))),
                            ArrayList::new));
            objectList.addAll(distinctList);
        }
        List<ExcelParseUtil.ExcelDataEntity> dataList = new ArrayList<>();
        dataList.add(ExcelParseUtil.toEntity("fileName", "原始字段"));
        if (LANGUAGE_PACK_CHINESE.equals(adminLanguagePack.getLanguagePackName())) {
            dataList.add(ExcelParseUtil.toEntity("chinese", "字段名称"));
        } else {
            dataList.add(ExcelParseUtil.toEntity("chinese", LANGUAGE_PACK_CHINESE));
        }
        dataList.add(ExcelParseUtil.toEntity("translateName", adminLanguagePack.getLanguagePackName()));
        ExcelParseUtil.exportExcel(objectList, new ExcelParseUtil.ExcelParseService() {
            @Override
            public String getExcelName() {
                return "语言包";
            }
        }, dataList);
    }


    /**
     * 解析json语言包
     */
    private Map<String, String> getFilePath(String languagePackContext) {
        JSONObject jsonObject = JSONObject.parseObject(languagePackContext, Feature.OrderedField);

        HashMap<String, String> fileMap = new LinkedHashMap<>();
        if (jsonObject != null) {
            for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
                Object o = entry.getValue();
                if (o instanceof String) {
                    fileMap.put(entry.getKey(), entry.getValue().toString());
                } else if (o instanceof JSONObject) {
                    JSONObject jsonObject2 = (JSONObject) o;
                    for (Map.Entry<String, Object> entry2 : jsonObject2.entrySet()) {
                        Object o2 = entry2.getValue();
                        if (o2 instanceof String) {
                            fileMap.put(entry.getKey() + "." + entry2.getKey(), entry2.getValue().toString());
                        }
                    }
                }
            }
        }
        return fileMap;
    }

    @Override
    public String queryLanguagePackContextById(Long id) {
        return getBaseMapper().queryLanguagePackById(id).getLanguagePackContext();
    }

    @Override
    public void downloadExcel(HttpServletResponse response) {
        List<Map<String, Object>> dataList = new ArrayList<>();
        try (ExcelWriter writer = ExcelUtil.getWriter()) {
            writer.addHeaderAlias("file", "原始字段");
            writer.addHeaderAlias("chinese", "中文");
            writer.addHeaderAlias("translate", "英语");
            Map<String, Object> record = new HashMap<>();
            record.put("file", "customer");
            record.put("chinese", "客户");
            record.put("translate", "Customer");
            dataList.add(record);
            writer.setOnlyAlias(true);
            writer.write(dataList, true);
            writer.setRowHeight(0, 20);
            int indexFor = 3;
            for (int i = 0; i < indexFor; i++) {
                writer.setColumnWidth(i, 30);
            }
            Cell cell = writer.getCell(0, 0);
            CellStyle cellStyle = cell.getCellStyle();
            cellStyle.setFillForegroundColor(IndexedColors.SKY_BLUE.getIndex());
            cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
            Font font = writer.createFont();
            font.setBold(true);
            font.setFontHeightInPoints((short) 16);
            cellStyle.setFont(font);
            cell.setCellStyle(cellStyle);
            //自定义标题别名
            //response为HttpServletResponse对象
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setCharacterEncoding("UTF-8");
            //test.xls是弹出下载对话框的文件名，不能为中文，中文请自行编码
            response.setHeader("Content-Disposition", "attachment;filename=languagePack_imp.xls");
            ServletOutputStream out = response.getOutputStream();
            writer.flush(out);
        } catch (Exception e) {
            log.error("导出语言包错误：", e);
        }
    }

    @Override
    public void updateLanguagePackNameById(AdminLanguagePackBO adminLanguagePackBO) {
        AdminLanguagePack oldAdminLanguagePac = lambdaQuery().ne(AdminLanguagePack::getLanguagePackId, adminLanguagePackBO.getLanguagePackId()).
                eq(AdminLanguagePack::getLanguagePackName, adminLanguagePackBO.getLanguagePackName()).one();
        if (oldAdminLanguagePac != null) {
            throw new CrmException(AdminCodeEnum.ADMIN_LANGUAGE_PACK_NAME_ERROR);
        }
        AdminLanguagePack languagePack = getBaseMapper().queryLanguagePackById(adminLanguagePackBO.getLanguagePackId());
        if (languagePack.getSysDefault().equals(SYSTEM)) {
            throw new CrmException(AdminCodeEnum.ADMIN_LANGUAGE_PACK_NAME_ERROR);
        }
        languagePack.setLanguagePackName(adminLanguagePackBO.getLanguagePackName());
        saveOrUpdate(languagePack);
    }

    @Override
    public OperationLog setDeflautLanguagePackSetting(Long id, Integer systemOrUser) {
        //修改默认语言 systemOrUser(0:系统用户， 1:个人用户)
        if (systemOrUser == SYSTEM) {
            AdminConfig adminConfig = adminConfigService.queryConfigByName(DEFAULT_LANGUAGE_PACK);
            if (adminConfig != null) {
                adminConfig.setValue(id.toString());
                adminConfigService.updateById(adminConfig);
            } else {
                adminConfig = new AdminConfig();
                adminConfig.setStatus(1);
                adminConfig.setName(DEFAULT_LANGUAGE_PACK);
                adminConfig.setValue(id.toString());
                adminConfig.setDescription(DEFAULT_LANGUAGE_PACK_DESCRIBE);
                adminConfigService.save(adminConfig);
            }
            AdminLanguagePack languagePack = adminLanguagePackService.getLanduagePackById(id);
            OperationLog operationLog = new OperationLog();
            if(ObjectUtil.isNotEmpty(languagePack)){
                operationLog.setOperationObject(languagePack.getLanguagePackName());
                operationLog.setOperationInfo("将" + languagePack.getLanguagePackName() + "设置为默认语言包");
            }
            return operationLog;

        } else if (systemOrUser == USER) {
            AdminUserConfig userConfig = adminUserConfigService.queryUserConfigByName(DEFAULT_LANGUAGE_PACK);
            if (userConfig != null) {
                userConfig.setValue(id.toString());
                adminUserConfigService.updateById(userConfig);
            } else {
                userConfig = new AdminUserConfig();
                userConfig.setStatus(1);
                userConfig.setName(DEFAULT_LANGUAGE_PACK);
                userConfig.setValue(id.toString());
                userConfig.setUserId(UserUtil.getUserId());
                userConfig.setDescription(DEFAULT_LANGUAGE_PACK_DESCRIBE);
                adminUserConfigService.save(userConfig);
            }
        }
        return null;
    }


    /**
     * 功能描述: <br>
     * 〈查询默认中文语言包〉
     *
     * @param: systemOrUser
     * @param: type
     * @param: needContext
     * @return: com.alibaba.fastjson.JSONObject
     * @throws:
     * @author: zyh
     * @date: 2022/8/6 16:35
     */
    @Override
    public JSONObject queryUserZhLanguage(Integer type, Boolean needContext) {
        long languagePackId = 0L;
        String languagePackName = null;
        String languagePackContext = null;
        String updateTime = null;
        PageEntity pageEntity = new PageEntity();
        pageEntity.setPageType(0);
        AdminLanguagePack pack = getBaseMapper().queryLanguagePack(1, LANGUAGE_PACK_CHINESE);
        if (BeanUtil.isNotEmpty(pack)) {
            languagePackId = pack.getLanguagePackId();
            languagePackName = pack.getLanguagePackName();
            languagePackContext = pack.getLanguagePackContext();
            updateTime = pack.getUpdateTime().toString();
        }
        JSONObject jsonObject = new JSONObject().fluentPut("languagePackId", languagePackId).fluentPut("languagePackName", languagePackName).fluentPut("updateTime", updateTime);
        if (ObjectUtil.isNotEmpty(needContext) && needContext) {
            jsonObject.fluentPut("languagePackContext", languagePackContext);
        }
        return jsonObject;
    }

    @Override
    public JSONObject queryDeflautLanguagePackSetting(Integer systemOrUser, Integer type, Boolean needContext) {
        //查询默认语言 systemOrUser(0:系统用户， 1:个人用户)
        long languagePackId = 0L;
        String languagePackName = null;
        String languagePackContext = null;
        String updateTime = null;

        if (systemOrUser == SYSTEM) {
            AdminConfig adminConfig = adminConfigService.queryConfigByName(DEFAULT_LANGUAGE_PACK);
            if (adminConfig != null) {
                languagePackId = Long.parseLong(adminConfig.getValue());
            } else {
                PageEntity pageEntity = new PageEntity();
                pageEntity.setPageType(0);
                List<AdminLanguagePackVO> packs = getBaseMapper().queryLanguagePackList(pageEntity.parse(), 1).getList();
                if (CollectionUtil.isNotEmpty(packs)) {
                    List<AdminLanguagePackVO> packVOS = packs.stream().filter(item -> LANGUAGE_PACK_CHINESE.equals(item.getLanguagePackName())).collect(Collectors.toList());
                    if (CollectionUtil.isEmpty(packVOS)) {
                        languagePackId = CollectionUtil.getFirst(packs).getLanguagePackId();
                    } else {
                        languagePackId = CollectionUtil.getFirst(packVOS).getLanguagePackId();
                    }
                }
            }

            AdminLanguagePack adminLanguagePack = this.lambdaQuery()
                    .select(AdminLanguagePack::getLanguagePackId, AdminLanguagePack::getLanguagePackName, AdminLanguagePack::getLanguagePackType)
                    .eq(AdminLanguagePack::getLanguagePackId, languagePackId).one();
            if (BeanUtil.isNotEmpty(adminLanguagePack)) {
                languagePackName = adminLanguagePack.getLanguagePackName();

                AdminLanguagePack adminLanguagePacks = getBaseMapper().queryLastLanguagePackByName(adminLanguagePack.getLanguagePackName(), type);
                if (ObjectUtil.isNotEmpty(adminLanguagePacks)) {
                    if (ObjectUtil.isNotEmpty(adminLanguagePacks.getUpdateTime())) {
                        updateTime = adminLanguagePacks.getUpdateTime().toString();
                    }
                }
            }
        } else if (systemOrUser == USER) {
            //个人和系统均有默认语言包，个人优先级高于系统
            AdminUserConfig userConfig = adminUserConfigService.queryUserConfigByName(DEFAULT_LANGUAGE_PACK);
            if (BeanUtil.isNotEmpty(userConfig)) {
                languagePackId = Long.parseLong(userConfig.getValue());
            } else {
                AdminConfig adminConfig = adminConfigService.queryConfigByName(DEFAULT_LANGUAGE_PACK);
                if (BeanUtil.isNotEmpty(adminConfig)) {
                    languagePackId = Long.parseLong(adminConfig.getValue());
                }
            }
            AdminLanguagePack adminLanguagePack = this.lambdaQuery()
                    .select(AdminLanguagePack::getLanguagePackId, AdminLanguagePack::getLanguagePackName, AdminLanguagePack::getLanguagePackType)
                    .eq(AdminLanguagePack::getLanguagePackId, languagePackId).one();
            //查询没有默认语言包是试用第一个语言包
            if (BeanUtil.isEmpty(adminLanguagePack)) {
                PageEntity pageEntity = new PageEntity();
                pageEntity.setPageType(0);
                List<AdminLanguagePackVO> packs = getBaseMapper().queryLanguagePackList(pageEntity.parse(), type).getList();
                if (CollectionUtil.isNotEmpty(packs)) {
                    //获取默认语言包，优先中文，如果没有中文选择最新更新的语言包
                    AdminLanguagePackVO first = CollectionUtil.getFirst(packs);
                    List<AdminLanguagePackVO> packVOS = packs.stream().filter(item -> LANGUAGE_PACK_CHINESE.equals(item.getLanguagePackName())).collect(Collectors.toList());
                    if (CollectionUtil.isNotEmpty(packVOS)) {
                        first = CollectionUtil.getFirst(packVOS);
                    }
                    adminLanguagePack = BeanUtil.copyProperties(first, AdminLanguagePack.class);
                    setDeflautLanguagePackSetting(adminLanguagePack.getLanguagePackId(), USER);
                }
            }
            if (BeanUtil.isNotEmpty(adminLanguagePack)) {
                languagePackName = adminLanguagePack.getLanguagePackName();

                AdminLanguagePack adminLanguagePacks = getBaseMapper().queryLastLanguagePackByName(adminLanguagePack.getLanguagePackName(), type);
                if (ObjectUtil.isNotEmpty(adminLanguagePacks)) {
                    if (ObjectUtil.isNotEmpty(adminLanguagePacks.getUpdateTime())) {
                        updateTime = adminLanguagePacks.getUpdateTime().toString();
                    }
                }
            }
        }
        JSONObject jsonObject = new JSONObject().fluentPut("languagePackId", languagePackId).fluentPut("languagePackName", languagePackName).fluentPut("updateTime", updateTime);
        if (ObjectUtil.isNotEmpty(needContext) && needContext) {
            AdminLanguagePack adminLanguagePack = getBaseMapper().queryLanguagePackById(languagePackId);
            jsonObject.fluentPut("languagePackContext", adminLanguagePack.getLanguagePackContext());
        }
        return jsonObject;
    }

    private String getFilePath(MultipartFile file) {
        String dirPath = FileUtil.getTmpDirPath();
        try {
            InputStream inputStream = file.getInputStream();
            File fromStream = FileUtil.writeFromStream(inputStream, dirPath + "/" + IdUtil.simpleUUID() + file.getOriginalFilename());
            return fromStream.getAbsolutePath();
        } catch (IOException e) {
            throw new CrmException(SystemCodeEnum.SYSTEM_UPLOAD_FILE_ERROR);
        }
    }

    @Override
    public void batchAddUpdateLanguageKey(AdminLanguagePackFieldBO languageVOS) {
        if (CollectionUtil.isEmpty(languageVOS.getMap())) {
            return;
        }
        //查询用户当前语言包是否是中文
        Long languagePackId = 0L;
        AdminUserConfig userConfig = adminUserConfigService.queryUserConfigByName(DEFAULT_LANGUAGE_PACK);
        if (BeanUtil.isNotEmpty(userConfig)) {
            languagePackId = Long.parseLong(userConfig.getValue());
        } else {
            AdminConfig adminConfig = adminConfigService.queryConfigByName(DEFAULT_LANGUAGE_PACK);
            if (BeanUtil.isNotEmpty(adminConfig)) {
                languagePackId = Long.parseLong(adminConfig.getValue());
            }
        }
        AdminLanguagePack defaultLanguagePack = getBaseMapper().queryLanguagePackById(languagePackId);
        if (BeanUtil.isEmpty(defaultLanguagePack) || !LANGUAGE_PACK_CHINESE.equals(defaultLanguagePack.getLanguagePackName())) {
            return;
        }
        AdminLanguagePack adminLanguagePack = new AdminLanguagePack();
        //获取语言包
        AdminLanguagePack adminLanguagePacks = getBaseMapper().queryLastLanguagePackByName(LANGUAGE_PACK_CHINESE, PC);
        if (ObjectUtil.isNotEmpty(adminLanguagePacks)) {
            adminLanguagePack = adminLanguagePacks;
        }
        String languagePackContext = adminLanguagePack.getLanguagePackContext();
        JSONObject jsonContext = JSONObject.parseObject(languagePackContext);
        jsonContext.putAll(languageVOS.getMap());
        //如果系统语言包则另存一份作为公司语言包 ，如果是公司语言包，则修改
        adminLanguagePack.setLanguagePackContext(jsonContext.toString());
        if (SYSTEM == adminLanguagePack.getSysDefault()) {
            AdminLanguagePack userLanguagePack = new AdminLanguagePack();
            userLanguagePack.setLanguagePackName(adminLanguagePack.getLanguagePackName());
            userLanguagePack.setLanguagePackContext(adminLanguagePack.getLanguagePackContext());
            userLanguagePack.setLanguagePackType(adminLanguagePack.getLanguagePackType());
            userLanguagePack.setSysDefault(USER);
            userLanguagePack.setCreateUserId(UserUtil.getUserId());
            userLanguagePack.setCreateTime(LocalDateTime.now());
            userLanguagePack.setUpdateTime(LocalDateTime.now());
            save(userLanguagePack);
        } else {
            adminLanguagePack.setUpdateTime(LocalDateTime.now());
            updateById(adminLanguagePack);
        }

    }

    @Override
    public JSONObject queryTypeContext(AdminLanguagePackTypeBO adminLanguagePackTypeBO) {
        if (ObjectUtil.isEmpty(adminLanguagePackTypeBO.getLanguagePackId())) {
            return new JSONObject();
        }
        AdminLanguagePack adminLanguagePack = getBaseMapper().queryLanguagePackById(adminLanguagePackTypeBO.getLanguagePackId());
        Integer type = adminLanguagePackTypeBO.getType();
        if (ObjectUtil.isEmpty(type)) {
            type = 0;
        }
        if (type.equals(0)) {
            return JSONObject.parseObject(adminLanguagePack.getLanguagePackContext());
        }
        if (type.equals(1)) {
            JSONObject jsonObject = JSONObject.parseObject(adminLanguagePack.getLanguagePackContext());
            Set<String> keys = jsonObject.keySet();
            if (CollectionUtil.isNotEmpty(keys)) {
                List<String> arrayList = CollectionUtil.newArrayList(keys);
                for (String key : arrayList) {
                    String[] filedNameArr = key.split(DEFAULT_SPLIT);
                    List<String> arrList = new ArrayList<>(Arrays.asList(filedNameArr));
                    if (!checkUuid(CollectionUtil.getLast(arrList))) {
                        jsonObject.remove(key);
                    }
                }
            }
            return jsonObject;
        }
        if (type.equals(2)) {
            JSONObject jsonObject = JSONObject.parseObject(adminLanguagePack.getLanguagePackContext());
            Set<String> keys = jsonObject.keySet();
            if (CollectionUtil.isNotEmpty(keys)) {
                List<String> arrayList = CollectionUtil.newArrayList(keys);
                for (String key : arrayList) {
                    String[] filedNameArr = key.split(DEFAULT_SPLIT);
                    List<String> arrList = new ArrayList<>(Arrays.asList(filedNameArr));
                    if (checkUuid(CollectionUtil.getLast(arrList))) {
                        jsonObject.remove(key);
                    }
                }
            }
            return jsonObject;
        }
        return new JSONObject();
    }


    @Override
    public JSONObject queryFilterContext() {
        JSONObject jsonObject = new JSONObject();
        List<AdminLanguagePack> chinesePacks = getBaseMapper().queryLanguagePackByName(LANGUAGE_PACK_CHINESE, null);
        List<AdminLanguagePack> enPacks = getBaseMapper().queryLanguagePackByName("en", null);
        chinesePacks.addAll(enPacks);
        //去除hrm,jxc,fn,
        for (AdminLanguagePack chinesePack : chinesePacks) {
            JSONObject parseObject = JSONObject.parseObject(chinesePack.getLanguagePackContext());
            Set<String> keys = parseObject.keySet();
            if (CollectionUtil.isNotEmpty(keys)) {
                List<String> arrayList = CollectionUtil.newArrayList(keys);
                for (String key : arrayList) {
                    if (key.startsWith("hrm.") || key.startsWith("jxc.") || key.startsWith("fm.") || key.startsWith("admin.hrm.") || key.startsWith("admin.finance.") || key.startsWith("admin.jxc.")
                            || key.startsWith("bi.hrm.") || key.startsWith("bi.finance.") || key.startsWith("bi.jxc.")
                    ) {
                        parseObject.remove(key);
                    }
                }
            }
            jsonObject.fluentPut(chinesePack.getLanguagePackName() + chinesePack.getLanguagePackType(), parseObject.toString());
        }
        return jsonObject;
    }

    @Override
    public AdminLanguagePack queryByName(AdminLanguagePackBO adminLanguagePackBO) {

        AdminLanguagePack languagePack = getBaseMapper().queryLastLanguagePackByName(adminLanguagePackBO.getLanguagePackName(), null);
        if (ObjectUtil.isEmpty(languagePack)) {
            return new AdminLanguagePack();
        }
        return languagePack;
    }

    /**
     * 功能描述:
     * 〈根据ID查询语言包：跳过租户隔离〉
     * @param id id
     * @return 正常返回:{@link AdminLanguagePack}
     * @author zyh
     */
    @Override
    public AdminLanguagePack getLanduagePackById(Long id) {
        return getBaseMapper().queryLanguagePackById(id);
    }

    public static boolean checkUuid(String uuid) {
        boolean isUuid = false;

        if (uuid.matches("([0-9a-fA-F]{8}(-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}?)")) {
            isUuid = true;
        }
        if (uuid.matches("([0-9a-fA-F]{8}([0-9a-fA-F]{4}){3}[0-9a-fA-F]{12}?)")) {
            isUuid = true;
        }

        return isUuid;
    }

}
